<template>
  <div class="novel-detail">
    <div class="novel-info">
      <div class="novel-cover">
        <img :src="novelInfo.coverUrl" alt="封面" />
        <div class="cover-overlay">
          <div class="status-badge" :class="{'ongoing': novelInfo.status === 1}">
            {{ novelInfo.status === 1 ? '连载中' : '已完结' }}
          </div>
        </div>
      </div>
      <div class="novel-content">
        <div class="novel-header">
          <h1 class="novel-title">{{ novelInfo.title }}</h1>
          <div class="novel-actions">
            <el-button 
              class="collect-btn" 
              :class="{ 'is-collected': isCollected }"
              @click="handleCollect"
              :icon="isCollected ? 'el-icon-star-on' : 'el-icon-star-off'"
            >
              {{ isCollected ? '已收藏' : '收藏' }}
            </el-button>
            <el-button 
              class="bookshelf-btn" 
              :class="{ 'in-bookshelf': inBookshelf }"
              @click="handleAddToBookshelf"
              :icon="inBookshelf ? 'el-icon-reading' : 'el-icon-plus'"
              plain
            >
              {{ inBookshelf ? '已在书架' : '加入书架' }}
            </el-button>
            <el-button 
              class="reward-btn" 
              type="danger"
              @click="showRewardDialog"
              icon="el-icon-present"
            >
              打赏
            </el-button>
            <el-button 
              class="pass-btn" 
              type="warning"
              @click="showPassDialog"
              icon="el-icon-ticket"
            >
              月票
            </el-button>
          </div>
        </div>
        <div class="novel-meta">
          <span class="author"><i class="el-icon-user"></i> {{ novelInfo.authorName }}</span>
          <span class="category"><i class="el-icon-collection-tag"></i> {{ novelInfo.categoryName }}</span>
        </div>
        <div class="novel-stats">
          <div class="stat-item">
            <i class="el-icon-document"></i>
            <span class="label">字数</span>
            <span class="value">{{ novelInfo.wordCount }}</span>
          </div>
          <div class="stat-item">
            <i class="el-icon-star-on"></i>
            <span class="label">收藏</span>
            <span class="value">{{ novelInfo.collection }}</span>
          </div>
          <div class="stat-item">
            <i class="el-icon-ticket"></i>
            <span class="label">月票</span>
            <span class="value">{{ novelInfo.pass }}</span>
          </div>
          <div class="stat-item">
            <i class="el-icon-view"></i>
            <span class="label">点击</span>
            <span class="value">{{ novelInfo.clicks }}</span>
          </div>
        </div>
        <div class="novel-description">
          <h3><i class="el-icon-reading"></i> 简介</h3>
          <p>{{ novelInfo.description }}</p>
        </div>
        <div class="update-time">
          <i class="el-icon-time"></i>
          更新时间：{{ formatDate(novelInfo.updateTime) }}
        </div>
      </div>
    </div>

    <!-- 章节列表 -->
    <div class="chapter-list">
      <div class="chapter-header">
        <h2><i class="el-icon-menu"></i> 目录</h2>
        <div class="chapter-filter">
          <span class="filter-item" :class="{ active: currentFilter === 'all' }" @click="currentFilter = 'all'">全部</span>
          <span class="filter-item" :class="{ active: currentFilter === 'free' }" @click="currentFilter = 'free'">免费</span>
          <span class="filter-item" :class="{ active: currentFilter === 'vip' }" @click="currentFilter = 'vip'">订阅</span>
        </div>
        <el-button type="primary" @click="showSubscribeDialog">订阅章节</el-button>
      </div>
      
      <!-- 章节范围选择 -->
      <div class="chapter-range">
        <div class="range-info">
          当前显示：{{ currentRangeStart }}-{{ currentRangeEnd }}章
        </div>
        <div class="range-selector">
          <span v-for="range in chapterRanges" 
                :key="range.start"
                class="range-item"
                :class="{ active: currentPage === range.page }"
                @click="currentPage = range.page">
            {{ range.start }}-{{ range.end }}章
          </span>
        </div>
      </div>

      <div class="chapter-grid">
        <div v-for="chapter in currentPageChapters" 
             :key="chapter.orderNum" 
             class="chapter-item"
             :class="{'vip-chapter': chapter.subscribe === 1}"
             @click="goToRead(chapter)">
          <span class="chapter-num">{{ chapter.orderNum }}</span>
          <span class="chapter-title">{{ chapter.chapterTitle }}</span>
          <span class="chapter-subscribe" :class="{'vip': chapter.subscribe === 1}">
            <i :class="chapter.subscribe === 1 ? 'el-icon-lock' : 'el-icon-unlock'"></i>
            {{ chapter.subscribe === 1 ? '订阅' : '免费' }}
          </span>
        </div>
      </div>
    </div>

    <!-- 评论区域 -->
    <div class="comment-section">
      <div class="comment-header">
        <h2><i class="el-icon-chat-dot-round"></i> 评论</h2>
        <div class="comment-count">{{ comments.length }} 条评论</div>
      </div>

      <!-- 评论输入框 -->
      <div class="comment-input">
        <el-input
          type="textarea"
          :rows="3"
          placeholder="写下你的评论..."
          v-model="newComment"
          maxlength="200"
          show-word-limit>
        </el-input>
        <div class="comment-input-actions">
          <el-button type="primary" @click="submitComment" :disabled="!newComment.trim()">
            发表评论
          </el-button>
        </div>
      </div>

      <!-- 评论列表 -->
      <div class="comment-list">
        <div v-for="comment in currentPageComments" :key="comment.id" class="comment-thread">
          <div class="comment-item">
            <div class="comment-avatar">
              <el-avatar :size="40" :src="comment.avatar" icon="el-icon-user-solid"></el-avatar>
            </div>
            <div class="comment-content">
              <div class="comment-header">
                <span class="comment-author">{{ comment.userName }}</span>
                <span class="comment-time">{{ formatDate(comment.createTime) }}</span>
              </div>
              <div class="comment-text">{{ comment.comment }}</div>
              <div class="comment-actions">
                <el-button type="text" size="small" @click="handleReply(comment)">
                  <i class="el-icon-chat-line-round"></i> 回复
                </el-button>
                <el-button v-if="userId === comment.userId" type="text" size="small" class="delete-btn" @click="handleDeleteComment(comment.id)">
                  <i class="el-icon-delete"></i> 删除
                </el-button>
              </div>
              <!-- 回复输入框 -->
              <div v-if="currentReplyId === comment.id" class="reply-input">
                <el-input
                  type="textarea"
                  :rows="2"
                  v-model="newComment"
                  placeholder="回复评论..."
                  maxlength="200"
                  show-word-limit
                ></el-input>
                <div class="reply-actions">
                  <el-button size="small" @click="cancelReply">取消</el-button>
                  <el-button type="primary" size="small" @click="submitComment" :disabled="!newComment.trim()">
                    回复
                  </el-button>
                </div>
              </div>
            </div>
          </div>
          <!-- 递归渲染子评论 -->
          <template v-if="comment.replies && comment.replies.length > 0">
            <div class="reply-list">
              <div v-for="reply in comment.replies" :key="reply.id" class="comment-thread">
                <div class="comment-item level-1">
                  <div class="comment-avatar">
                    <el-avatar :size="36" :src="reply.avatar" icon="el-icon-user-solid"></el-avatar>
                  </div>
                  <div class="comment-content">
                    <div class="comment-header">
                      <span class="comment-author">{{ reply.userName }}</span>
                      <span class="comment-time">{{ formatDate(reply.createTime) }}</span>
                    </div>
                    <div class="comment-text">{{ reply.comment }}</div>
                    <div class="comment-actions">
                      <el-button type="text" size="small" @click="handleReply(reply)">
                        <i class="el-icon-chat-line-round"></i> 回复
                      </el-button>
                      <el-button v-if="userId === reply.userId" type="text" size="small" class="delete-btn" @click="handleDeleteComment(reply.id)">
                        <i class="el-icon-delete"></i> 删除
                      </el-button>
                    </div>
                    <!-- 回复输入框 -->
                    <div v-if="currentReplyId === reply.id" class="reply-input">
                      <el-input
                        type="textarea"
                        :rows="2"
                        v-model="newComment"
                        placeholder="回复评论..."
                        maxlength="200"
                        show-word-limit
                      ></el-input>
                      <div class="reply-actions">
                        <el-button size="small" @click="cancelReply">取消</el-button>
                        <el-button type="primary" size="small" @click="submitComment" :disabled="!newComment.trim()">
                          回复
                        </el-button>
                      </div>
                    </div>
                  </div>
                </div>
                <!-- 递归渲染二级回复 -->
                <template v-if="reply.replies && reply.replies.length > 0">
                  <div class="reply-list">
                    <div v-for="subReply in reply.replies" :key="subReply.id" class="comment-thread">
                      <div class="comment-item level-2">
                        <div class="comment-avatar">
                          <el-avatar :size="32" :src="subReply.avatar" icon="el-icon-user-solid"></el-avatar>
                        </div>
                        <div class="comment-content">
                          <div class="comment-header">
                            <span class="comment-author">{{ subReply.userName }}</span>
                            <span class="comment-time">{{ formatDate(subReply.createTime) }}</span>
                          </div>
                          <div class="comment-text">{{ subReply.comment }}</div>
                          <div class="comment-actions">
                            <el-button type="text" size="small" @click="handleReply(subReply)">
                              <i class="el-icon-chat-line-round"></i> 回复
                            </el-button>
                            <el-button v-if="userId === subReply.userId" type="text" size="small" class="delete-btn" @click="handleDeleteComment(subReply.id)">
                              <i class="el-icon-delete"></i> 删除
                            </el-button>
                          </div>
                          <!-- 回复输入框 -->
                          <div v-if="currentReplyId === subReply.id" class="reply-input">
                            <el-input
                              type="textarea"
                              :rows="2"
                              v-model="newComment"
                              placeholder="回复评论..."
                              maxlength="200"
                              show-word-limit
                            ></el-input>
                            <div class="reply-actions">
                              <el-button size="small" @click="cancelReply">取消</el-button>
                              <el-button type="primary" size="small" @click="submitComment" :disabled="!newComment.trim()">
                                回复
                              </el-button>
                            </div>
                          </div>
                        </div>
                      </div>
                      <!-- 递归渲染三级回复 -->
                      <template v-if="subReply.replies && subReply.replies.length > 0">
                        <div class="reply-list">
                          <div v-for="thirdReply in subReply.replies" :key="thirdReply.id" class="comment-thread">
                            <div class="comment-item level-3">
                              <div class="comment-avatar">
                                <el-avatar :size="28" :src="thirdReply.avatar" icon="el-icon-user-solid"></el-avatar>
                              </div>
                              <div class="comment-content">
                                <div class="comment-header">
                                  <span class="comment-author">{{ thirdReply.userName }}</span>
                                  <span class="comment-time">{{ formatDate(thirdReply.createTime) }}</span>
                                </div>
                                <div class="comment-text">{{ thirdReply.comment }}</div>
                                <div class="comment-actions">
                                  <el-button type="text" size="small" @click="handleReply(thirdReply)">
                                    <i class="el-icon-chat-line-round"></i> 回复
                                  </el-button>
                                  <el-button v-if="userId === thirdReply.userId" type="text" size="small" class="delete-btn" @click="handleDeleteComment(thirdReply.id)">
                                    <i class="el-icon-delete"></i> 删除
                                  </el-button>
                                </div>
                                <!-- 回复输入框 -->
                                <div v-if="currentReplyId === thirdReply.id" class="reply-input">
                                  <el-input
                                    type="textarea"
                                    :rows="2"
                                    v-model="newComment"
                                    placeholder="回复评论..."
                                    maxlength="200"
                                    show-word-limit
                                  ></el-input>
                                  <div class="reply-actions">
                                    <el-button size="small" @click="cancelReply">取消</el-button>
                                    <el-button type="primary" size="small" @click="submitComment" :disabled="!newComment.trim()">
                                      回复
                                    </el-button>
                                  </div>
                                </div>
                              </div>
                            </div>
                            <!-- 递归渲染四级回复 -->
                            <template v-if="thirdReply.replies && thirdReply.replies.length > 0">
                              <div class="reply-list">
                                <div v-for="fourthReply in thirdReply.replies" :key="fourthReply.id" class="comment-thread">
                                  <div class="comment-item level-4">
                                    <div class="comment-avatar">
                                      <el-avatar :size="24" :src="fourthReply.avatar" icon="el-icon-user-solid"></el-avatar>
                                    </div>
                                    <div class="comment-content">
                                      <div class="comment-header">
                                        <span class="comment-author">{{ fourthReply.userName }}</span>
                                        <span class="comment-time">{{ formatDate(fourthReply.createTime) }}</span>
                                      </div>
                                      <div class="comment-text">{{ fourthReply.comment }}</div>
                                      <div class="comment-actions">
                                        <el-button type="text" size="small" @click="handleReply(fourthReply)">
                                          <i class="el-icon-chat-line-round"></i> 回复
                                        </el-button>
                                        <el-button v-if="userId === fourthReply.userId" type="text" size="small" class="delete-btn" @click="handleDeleteComment(fourthReply.id)">
                                          <i class="el-icon-delete"></i> 删除
                                        </el-button>
                                      </div>
                                      <!-- 回复输入框 -->
                                      <div v-if="currentReplyId === fourthReply.id" class="reply-input">
                                        <el-input
                                          type="textarea"
                                          :rows="2"
                                          v-model="newComment"
                                          placeholder="回复评论..."
                                          maxlength="200"
                                          show-word-limit
                                        ></el-input>
                                        <div class="reply-actions">
                                          <el-button size="small" @click="cancelReply">取消</el-button>
                                          <el-button type="primary" size="small" @click="submitComment" :disabled="!newComment.trim()">
                                            回复
                                          </el-button>
                                        </div>
                                      </div>
                                    </div>
                                  </div>
                                </div>
                              </div>
                            </template>
                          </div>
                        </div>
                      </template>
                    </div>
                  </div>
                </template>
              </div>
            </div>
          </template>
        </div>
      </div>

      <!-- 评论分页 -->
      <div class="comment-pagination">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="currentPage"
          :page-sizes="[10, 20, 30, 50]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="comments.length">
        </el-pagination>
      </div>
    </div>

    <!-- 订阅弹窗 -->
    <el-dialog title="订阅章节" :visible.sync="subscribeDialogVisible" width="50%">
      <el-table :data="subscribeList" style="width: 100%" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55"></el-table-column>
        <el-table-column prop="orderNum" label="章节序号" width="120"></el-table-column>
        <el-table-column prop="chapterTitle" label="章节标题"></el-table-column>
        <el-table-column prop="subscribe" label="订阅状态" width="100">
          <template slot-scope="scope">
            <el-tag type="info">未订阅</el-tag>
          </template>
        </el-table-column>
      </el-table>
      <div class="subscribe-info">
        <p>已选择 {{ selectedChapters.length }} 章，需要消耗 {{ selectedChapters.length * 10 }} 积分</p>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="subscribeDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="handleSubscribe" :disabled="selectedChapters.length === 0">确认订阅</el-button>
      </span>
    </el-dialog>

    <!-- 打赏弹窗 -->
    <el-dialog title="打赏作者" :visible.sync="rewardDialogVisible" width="400px">
      <div class="reward-dialog">
        <div class="reward-options">
          <div 
            v-for="(option, index) in rewardOptions" 
            :key="index"
            class="reward-option"
            :class="{ active: selectedReward === option.value }"
            @click="selectedReward = option.value"
          >
            <div class="reward-icon">
              <i :class="option.icon"></i>
            </div>
            <div class="reward-value">{{ option.label }}</div>
            <div class="reward-points">{{ option.value }} 积分</div>
          </div>
        </div>
        <div class="reward-message">
          <el-input
            type="textarea"
            :rows="2"
            placeholder="写下你的打赏留言（选填）..."
            v-model="rewardMessage"
            maxlength="100"
            show-word-limit
          ></el-input>
        </div>
        <div class="reward-info">
          <p>当前积分余额：{{ userPoints }} 积分</p>
          <p>打赏后剩余：{{ userPoints - selectedReward }} 积分</p>
        </div>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="rewardDialogVisible = false">取 消</el-button>
        <el-button type="danger" @click="handleReward" :disabled="selectedReward === 0 || userPoints < selectedReward">
          确认打赏
        </el-button>
      </span>
    </el-dialog>

    <!-- 月票打赏弹窗 -->
    <el-dialog title="月票打赏" :visible.sync="passDialogVisible" width="400px">
      <div class="pass-dialog">
        <div class="pass-options">
          <div class="pass-input">
            <span class="pass-label">月票数量：</span>
            <el-input-number 
              v-model="passCount" 
              :min="1" 
              :max="100" 
              @change="calculatePassPoints"
              size="medium"
            ></el-input-number>
          </div>
          <div class="pass-info">
            <p>每张月票需要 10 积分</p>
            <p>当前积分余额：{{ userPoints }} 积分</p>
            <p>所需积分：{{ passPoints }} 积分</p>
            <p>打赏后剩余：{{ userPoints - passPoints }} 积分</p>
          </div>
        </div>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="passDialogVisible = false">取 消</el-button>
        <el-button type="warning" @click="handlePass" :disabled="passCount === 0 || userPoints < passPoints">
          确认打赏
        </el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { getNovelContent, getNovelChapter } from "@/api/novel/novel";
import { addCollection, cancelCollection, isCollection, getCommentList, addComment, deleteComment, getSubscribeList, subscribe, pass, addBookShelf, isInBookShelf, deleteBookShelf, deleteBatchBookShelf } from "@/api/bookshelf/bookshelf";
import { getPointsByUserId, reward } from "@/api/points/points";
import store from "@/store";

export default {
  name: "NovelDetail",
  components: {
  },
  data() {
    return {
      userId: store.state.user.id,
      novelInfo: {
        title: '',
        authorName: '',
        categoryName: '',
        description: '',
        coverUrl: '',
        wordCount: 0,
        collection: 0,
        pass: 0,
        status: 0,
        updateTime: '',
        clicks: 0
      },
      chapters: [],
      currentFilter: 'all',
      currentPage: 1,
      pageSize: 10,
      isCollected: false,
      loading: false,
      comments: [], // 评论列表
      currentReplyId: null, // 当前回复的评论ID
      newComment: '', // 新评论内容
      isReplying: false, // 是否正在回复
      totalComments: 0, // 评论总数
      expandedComments: [], // 改为数组存储展开的评论ID
      subscribeDialogVisible: false,
      subscribeList: [],
      selectedChapters: [],
      // 打赏相关
      rewardDialogVisible: false,
      rewardOptions: [
        { label: '鲜花', value: 10, icon: 'el-icon-flower' },
        { label: '咖啡', value: 30, icon: 'el-icon-coffee-cup' },
        { label: '蛋糕', value: 50, icon: 'el-icon-food' },
        { label: '皇冠', value: 100, icon: 'el-icon-trophy' },
        { label: '火箭', value: 500, icon: 'el-icon-rocket' }
      ],
      selectedReward: 0,
      rewardMessage: '',
      userPoints: 0,
      // 月票相关
      passDialogVisible: false,
      passCount: 1,
      passPoints: 10,
      inBookshelf: false
    };
  },
  computed: {
    filteredChapters() {
      if (this.currentFilter === 'all') return this.chapters;
      return this.chapters.filter(chapter => 
        this.currentFilter === 'free' ? chapter.subscribe === 0 : chapter.subscribe === 1
      );
    },
    totalPages() {
      return Math.ceil(this.filteredChapters.length / this.pageSize);
    },
    chapterRanges() {
      const ranges = [];
      for (let i = 0; i < this.totalPages; i++) {
        const start = i * this.pageSize + 1;
        const end = Math.min((i + 1) * this.pageSize, this.filteredChapters.length);
        ranges.push({
          page: i + 1,
          start,
          end
        });
      }
      return ranges;
    },
    currentRangeStart() {
      return (this.currentPage - 1) * this.pageSize + 1;
    },
    currentRangeEnd() {
      return Math.min(this.currentPage * this.pageSize, this.filteredChapters.length);
    },
    currentPageChapters() {
      const start = (this.currentPage - 1) * this.pageSize;
      const end = start + this.pageSize;
      return this.filteredChapters.slice(start, end);
    },
    currentPageComments() {
      const start = (this.currentPage - 1) * this.pageSize;
      const end = start + this.pageSize;
      return this.comments.slice(start, end);
    },
    // 计算总评论数（只计算主评论）
    totalCommentCount() {
      return this.comments.length;
    }
  },
  created() {
    this.getNovelInfo();
    this.getComments();
  },
  watch: {
    'novelInfo.title': {
      handler(newVal) {
        if (newVal) {
          this.checkBookshelfStatus();
        }
      },
      immediate: true
    },
    userId: {
      handler(newVal) {
        if (newVal) {
          this.checkBookshelfStatus();
        }
      },
      immediate: true
    }
  },
  methods: {
    getNovelInfo() {
      const title = this.$route.query.title;
      if (!title) {
        this.$message.error('小说标题不能为空');
        return;
      }
      
      if (this.loading) {
        return;
      }
      
      this.loading = true;
      
      // 获取小说基本信息
      getNovelContent(title).then(response => {
        if (response.data) {
          this.novelInfo = response.data;
          // 检查是否已收藏
          if (this.userId) {
            isCollection({
              userId: this.userId,
              novelName: title
            }).then(response => {
              if (response.data && response.data.data !== undefined) {
                this.isCollected = response.data.data === 1;
              }
            });
          }
        }
      }).catch(error => {
        console.error('获取小说信息失败:', error);
        this.$message.error('获取小说信息失败');
      }).finally(() => {
        this.loading = false;
      });
      
      // 获取章节列表
      getNovelChapter(title).then(response => {
        if (response.rows) {
          this.chapters = response.rows;
        }
      }).catch(error => {
        console.error('获取章节列表失败:', error);
        this.$message.error('获取章节列表失败');
      });
    },
    formatDate(date) {
      if (!date) return '';
      const d = new Date(date);
      return d.getFullYear() + '-' +
        String(d.getMonth() + 1).padStart(2, '0') + '-' +
        String(d.getDate()).padStart(2, '0') + ' ' +
        String(d.getHours()).padStart(2, '0') + ':' +
        String(d.getMinutes()).padStart(2, '0');
    },
    /** 处理收藏/取消收藏 */
    handleCollect() {
      if (!this.userId) {
        this.$message.warning('请先登录');
        return;
      }
      
      if (this.isCollected) {
        // 取消收藏
        cancelCollection({
          userId: this.userId,
          novelName: this.novelInfo.title
        }).then(response => {
          this.isCollected = false;
          this.$message.success('取消收藏成功');
          // 刷新页面以更新收藏数
          this.getNovelInfo();
        }).catch(error => {
          this.$message.error('取消收藏失败：' + error.message);
        });
      } else {
        // 添加收藏
        addCollection({
          userId: this.userId,
          novelName: this.novelInfo.title
        }).then(response => {
          this.isCollected = true;
          this.$message.success('收藏成功');
          // 刷新页面以更新收藏数
          this.getNovelInfo();
        }).catch(error => {
          this.$message.error('收藏失败：' + error.message);
        });
      }
    },
    goToRead(chapter) {
      if (!chapter) {
        this.$message.error('章节信息无效');
        return;
      }
      
      // 确保参数正确
      const title = this.novelInfo.title;
      const orderNum = chapter.orderNum;
      
      if (!title || !orderNum) {
        this.$message.error('章节信息不完整');
        return;
      }
      
      console.log('跳转到阅读页面，参数:', { title, orderNum });
      
      // 使用replace而不是push，避免在历史记录中留下无效的页面
      this.$router.replace({
        path: '/novel/read',
        query: { title, orderNum }
      });
    },
    /** 获取评论列表 */
    async getComments() {
      const title = this.$route.query.title;
      if (!title) return;
      
      try {
        const response = await getCommentList(title);
        console.log('评论数据:', response); // 添加日志
        if (response.code === 200 && response.data) {
          // 直接使用原始评论数据，不进行处理
          this.comments = response.data;
          this.totalComments = this.comments.length;
        }
      } catch (error) {
        console.error('获取评论失败:', error);
        this.$message.error('获取评论失败');
      }
    },
    /** 处理每页显示数量变化 */
    handleSizeChange(val) {
      this.pageSize = val;
      this.currentPage = 1; // 重置到第一页
    },
    /** 处理页码变化 */
    handleCurrentChange(val) {
      this.currentPage = val;
      // 滚动到评论区域顶部
      this.$nextTick(() => {
        const commentSection = document.querySelector('.comment-section');
        if (commentSection) {
          commentSection.scrollIntoView({ behavior: 'smooth' });
        }
      });
    },
    /** 提交评论 */
    submitComment() {
      if (!this.userId) {
        this.$message.warning('请先登录');
        return;
      }

      if (!this.newComment.trim()) {
        this.$message.warning('评论内容不能为空');
        return;
      }

      const commentData = {
        userId: this.userId,
        title: this.novelInfo.title,
        comment: this.newComment.trim(),
        parentId: this.currentReplyId || null
      };

      console.log('提交评论数据:', commentData); // 添加日志

      addComment(commentData).then(response => {
        if (response.code === 200) {
          this.$message.success('评论成功');
          this.newComment = '';
          this.currentReplyId = null;
          this.getComments(); // 刷新评论列表
        } else {
          this.$message.error(response.msg || '评论失败');
        }
      }).catch(error => {
        console.error('评论失败:', error);
        this.$message.error('评论失败');
      });
    },
    /** 处理回复 */
    handleReply(comment) {
      this.currentReplyId = comment.id;
      this.isReplying = true;
      this.newComment = `回复 ${comment.userName}：`;
    },
    /** 取消回复 */
    cancelReply() {
      this.currentReplyId = null;
      this.isReplying = false;
      this.newComment = '';
    },
    /** 检查评论是否展开 */
    isCommentExpanded(commentId) {
      return this.expandedComments.includes(commentId);
    },
    /** 切换评论展开状态 */
    toggleComment(commentId) {
      const index = this.expandedComments.indexOf(commentId);
      if (index > -1) {
        this.expandedComments.splice(index, 1);
      } else {
        this.expandedComments.push(commentId);
      }
    },
    /** 计算评论的回复总数（包括子回复） */
    countReplies(comment) {
      let count = 0;
      if (comment.replies) {
        count += comment.replies.length;
        comment.replies.forEach(reply => {
          count += this.countReplies(reply);
        });
      }
      return count;
    },
    /** 获取所有回复（包括子回复） */
    getAllReplies(comment) {
      let allReplies = [];
      if (comment.replies) {
        comment.replies.forEach(reply => {
          allReplies.push(reply);
          if (reply.replies) {
            allReplies = allReplies.concat(this.getAllReplies(reply));
          }
        });
      }
      return allReplies;
    },
    /** 处理删除评论 */
    handleDeleteComment(commentId) {
      if (!this.userId) {
        this.$message.warning('请先登录');
        return;
      }
      
      this.$confirm('确定要删除这条评论吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        console.log('正在删除评论，ID:', commentId);
        deleteComment(commentId).then(response => {
          console.log('删除评论响应:', response);
          if (response.code === 200) {
            this.$message.success('删除成功');
            // 刷新评论列表
            this.getComments().then(() => {
              // 重置到第一页
              this.currentPage = 1;
              // 清空展开状态
              this.expandedComments = [];
            });
          } else {
            this.$message.error('删除失败: ' + (response.msg || '未知错误'));
          }
        }).catch(error => {
          console.error('删除评论失败:', error);
          this.$message.error('删除评论失败: ' + (error.message || '未知错误'));
        });
      }).catch(() => {
        // 用户取消删除操作
        console.log('用户取消删除操作');
      });
    },
    // 显示订阅弹窗
    showSubscribeDialog() {
      this.subscribeDialogVisible = true;
      this.getSubscribeList();
    },
    
    // 获取未订阅章节列表
    getSubscribeList() {
      getSubscribeList(this.userId, this.novelInfo.title)
        .then(response => {
          if (response.code === 200) {
            this.subscribeList = response.data;
          }
        })
        .catch(error => {
          console.error('获取订阅列表失败:', error);
          this.$message.error("获取订阅列表失败");
        });
    },
    
    // 处理章节选择变化
    handleSelectionChange(selection) {
      this.selectedChapters = selection.map(item => item.orderNum);
    },
    
    // 处理订阅
    handleSubscribe() {
      if (this.selectedChapters.length === 0) {
        this.$message.warning("请选择要订阅的章节");
        return;
      }
      
      const subscribeData = {
        userId: this.userId,
        orderNum: this.selectedChapters,
        novelName: this.novelInfo.title,
        points: this.selectedChapters.length * 10
      };
      
      subscribe(subscribeData)
        .then(response => {
          if (response.code === 200) {
            this.$message.success("订阅成功");
            this.subscribeDialogVisible = false;
            this.getSubscribeList(); // 刷新订阅列表
          } else {
            this.$message.error(response.msg || "订阅失败");
          }
        })
        .catch(error => {
          console.error('订阅失败:', error);
          this.$message.error("订阅失败");
        });
    },
    /** 获取用户积分 */
    getUserPoints() {
      if (!this.userId) return;
      
      getPointsByUserId(this.userId).then(response => {
        if (response.code === 200 && response.data) {
          this.userPoints = response.data.points || 0;
        }
      }).catch(error => {
        console.error('获取用户积分失败:', error);
      });
    },
    
    /** 显示打赏弹窗 */
    showRewardDialog() {
      if (!this.userId) {
        this.$message.warning('请先登录');
        return;
      }
      
      this.rewardDialogVisible = true;
      this.selectedReward = 0;
      this.rewardMessage = '';
      this.getUserPoints(); // 刷新用户积分
    },
    
    /** 处理打赏 */
    handleReward() {
      if (!this.userId) {
        this.$message.warning('请先登录');
        return;
      }
      
      if (this.selectedReward <= 0) {
        this.$message.warning('请选择打赏金额');
        return;
      }
      
      if (this.userPoints < this.selectedReward) {
        this.$message.warning('积分不足，请充值');
        return;
      }
      
      const rewardData = {
        userId: this.userId,
        novelName: this.novelInfo.title,
        points: this.selectedReward,
        message: this.rewardMessage.trim() || null
      };
      
      reward(rewardData).then(response => {
        if (response.code === 200) {
          this.$message.success('打赏成功');
          this.rewardDialogVisible = false;
          this.getUserPoints(); // 刷新用户积分
          // 刷新小说信息以更新打赏数
          this.getNovelInfo();
        } else {
          this.$message.error(response.msg || '打赏失败');
        }
      }).catch(error => {
        console.error('打赏失败:', error);
        this.$message.error('打赏失败');
      });
    },
    /** 显示月票打赏弹窗 */
    showPassDialog() {
      if (!this.userId) {
        this.$message.warning('请先登录');
        return;
      }
      
      this.passDialogVisible = true;
      this.passCount = 1;
      this.calculatePassPoints();
      this.getUserPoints(); // 刷新用户积分
    },
    
    /** 计算月票所需积分 */
    calculatePassPoints() {
      this.passPoints = this.passCount * 10;
    },
    
    /** 处理月票打赏 */
    handlePass() {
      if (!this.userId) {
        this.$message.warning('请先登录');
        return;
      }
      
      if (this.passCount <= 0) {
        this.$message.warning('请选择月票数量');
        return;
      }
      
      if (this.userPoints < this.passPoints) {
        this.$message.warning('积分不足，请充值');
        return;
      }
      
      const passData = {
        userId: this.userId,
        novelName: this.novelInfo.title,
        points: this.passPoints,
        pass: this.passCount
      };
      
      pass(passData).then(response => {
        if (response.code === 200) {
          this.$message.success('月票打赏成功');
          this.passDialogVisible = false;
          this.getUserPoints(); // 刷新用户积分
          // 刷新小说信息以更新月票数
          this.getNovelInfo();
        } else {
          this.$message.error(response.msg || '月票打赏失败');
        }
      }).catch(error => {
        console.error('月票打赏失败:', error);
        this.$message.error('月票打赏失败');
      });
    },
    /** 处理加入书架 */
    handleAddToBookshelf() {
      if (!this.userId) {
        this.$message.warning('请先登录');
        return;
      }
      
      if (this.inBookshelf) {
        this.$confirm('确定要从书架中移除该小说吗？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          deleteBookShelf(this.userId, this.novelInfo.title).then(response => {
            if (response.code === 200) {
              this.inBookshelf = false;
              this.$message.success('已从书架移除');
            } else {
              this.$message.error(response.msg || '移除失败');
            }
          }).catch(error => {
            console.error('移除失败:', error);
            this.$message.error('移除失败');
          });
        }).catch(() => {
          // 用户取消操作
        });
      } else {
        addBookShelf(this.userId, this.novelInfo.title).then(response => {
          if (response.code === 200) {
            this.inBookshelf = true;
            this.$message.success('已加入书架');
          } else {
            this.$message.error(response.msg || '加入书架失败');
          }
        }).catch(error => {
          console.error('加入书架失败:', error);
          this.$message.error('加入书架失败');
        });
      }
    },
    /** 检查是否在书架中 */
    checkBookshelfStatus() {
      if (!this.userId || !this.novelInfo.title) return;
      
      isInBookShelf(this.userId, this.novelInfo.title).then(response => {
        if (response.code === 200) {
          this.inBookshelf = response.data === 1;
        }
      }).catch(error => {
        console.error('检查书架状态失败:', error);
      });
    }
  }
};
</script>

<style scoped>
.novel-detail {
  padding: 20px;
  max-width: 1200px;
  margin: 0 auto;
  background: #f8f9fa;
  min-height: 100vh;
}

.novel-info {
  display: flex;
  gap: 30px;
  margin-bottom: 40px;
  background: #fff;
  padding: 30px;
  border-radius: 12px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
  position: relative;
  overflow: hidden;
}

.novel-cover {
  width: 240px;
  height: 320px;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  position: relative;
}

.novel-cover img {
  width: 100%;
  height: 100%;
  object-fit: cover;
  transition: transform 0.3s ease;
}

.novel-cover:hover img {
  transform: scale(1.05);
}

.cover-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: linear-gradient(to bottom, rgba(0,0,0,0.2), transparent);
  display: flex;
  align-items: flex-start;
  justify-content: flex-end;
  padding: 10px;
}

.status-badge {
  background: #67c23a;
  color: white;
  padding: 4px 12px;
  border-radius: 12px;
  font-size: 12px;
  font-weight: 500;
}

.status-badge.ongoing {
  background: #f56c6c;
}

.novel-content {
  flex: 1;
}

.novel-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.novel-title {
  font-size: 32px;
  color: #2c3e50;
  margin-bottom: 20px;
  font-weight: 600;
  line-height: 1.2;
}

.novel-meta {
  display: flex;
  gap: 20px;
  margin-bottom: 20px;
  color: #606f7b;
  font-size: 14px;
}

.novel-meta i {
  margin-right: 5px;
}

.novel-stats {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 20px;
  margin-bottom: 30px;
  padding: 20px;
  background: #f8f9fa;
  border-radius: 12px;
}

.stat-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  text-align: center;
}

.stat-item i {
  font-size: 24px;
  color: #f56c6c;
  margin-bottom: 8px;
}

.stat-item .label {
  font-size: 12px;
  color: #909399;
  margin-bottom: 4px;
}

.stat-item .value {
  font-size: 18px;
  color: #2c3e50;
  font-weight: 600;
}

.novel-description {
  margin-bottom: 30px;
  padding: 20px;
  background: #f8f9fa;
  border-radius: 12px;
}

.novel-description h3 {
  font-size: 18px;
  color: #2c3e50;
  margin-bottom: 15px;
  display: flex;
  align-items: center;
  gap: 8px;
}

.novel-description p {
  color: #606f7b;
  line-height: 1.8;
  text-align: justify;
}

.update-time {
  color: #909399;
  font-size: 14px;
  display: flex;
  align-items: center;
  gap: 5px;
}

/* 章节列表样式 */
.chapter-list {
  background: #fff;
  padding: 30px;
  border-radius: 12px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
}

.chapter-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.chapter-header h2 {
  font-size: 24px;
  color: #2c3e50;
  display: flex;
  align-items: center;
  gap: 8px;
}

.chapter-filter {
  display: flex;
  gap: 15px;
}

.filter-item {
  padding: 6px 16px;
  border-radius: 20px;
  cursor: pointer;
  transition: all 0.3s ease;
  font-size: 14px;
  color: #606f7b;
}

.filter-item:hover {
  background: #f0f2f5;
}

.filter-item.active {
  background: #f56c6c;
  color: white;
}

.chapter-grid {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 12px;
}

.chapter-item {
  display: flex;
  align-items: center;
  padding: 12px 15px;
  background: #f8f9fa;
  border-radius: 8px;
  transition: all 0.3s ease;
  cursor: pointer;
  border: 1px solid transparent;
}

.chapter-item:hover {
  background: #fff5f5;
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(245, 108, 108, 0.1);
  border-color: #f56c6c;
}

.chapter-item.vip-chapter {
  background: #fff9f0;
}

.chapter-num {
  color: #f56c6c;
  font-weight: 600;
  margin-right: 12px;
  min-width: 50px;
  font-size: 14px;
}

.chapter-title {
  flex: 1;
  color: #2c3e50;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  font-size: 14px;
}

.chapter-subscribe {
  font-size: 12px;
  color: #67c23a;
  background: #f0f9eb;
  padding: 4px 10px;
  border-radius: 12px;
  margin-left: 8px;
  display: flex;
  align-items: center;
  gap: 4px;
  white-space: nowrap;
}

.chapter-subscribe.vip {
  color: #e6a23c;
  background: #fdf6ec;
}

.chapter-subscribe i {
  font-size: 14px;
}

/* 章节范围选择器样式 */
.chapter-range {
  margin-bottom: 20px;
  padding: 15px;
  background: #f8f9fa;
  border-radius: 8px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.range-info {
  color: #606f7b;
  font-size: 14px;
  font-weight: 500;
}

.range-selector {
  display: flex;
  gap: 10px;
  flex-wrap: wrap;
}

.range-item {
  padding: 6px 12px;
  border-radius: 16px;
  background: #fff;
  color: #606f7b;
  font-size: 13px;
  cursor: pointer;
  transition: all 0.3s ease;
  border: 1px solid #e4e7ed;
}

.range-item:hover {
  background: #f0f2f5;
  border-color: #dcdfe6;
}

.range-item.active {
  background: #f56c6c;
  color: white;
  border-color: #f56c6c;
}

.collect-btn {
  padding: 10px 20px;
  border-radius: 20px;
  transition: all 0.3s ease;
  border: 1px solid #dcdfe6;
  background: #fff;
  color: #606f7b;
}

.collect-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.collect-btn.is-collected {
  background: #f56c6c;
  color: white;
  border-color: #f56c6c;
}

.collect-btn.is-collected:hover {
  background: #f78989;
}

.collect-btn i {
  margin-right: 5px;
}

/* 评论区域样式 */
.comment-section {
  margin-top: 40px;
  background: #fff;
  padding: 30px;
  border-radius: 12px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.comment-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 30px;
  padding-bottom: 15px;
  border-bottom: 2px solid #eef2f7;
}

.comment-header h2 {
  font-size: 24px;
  color: #2c3e50;
  display: flex;
  align-items: center;
  gap: 8px;
  margin: 0;
}

.comment-count {
  color: #909399;
  font-size: 14px;
}

.comment-input {
  margin-bottom: 30px;
  background: #fff;
  padding: 20px;
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

.comment-input-actions {
  display: flex;
  justify-content: flex-end;
  margin-top: 10px;
}

.comment-list {
  display: flex;
  flex-direction: column;
  gap: 25px;
}

.comment-thread {
  margin-bottom: 20px;
}

.comment-item {
  display: flex;
  gap: 16px;
  padding: 16px;
  background: #f8f9fa;
  border-radius: 8px;
  position: relative;
}

.comment-avatar {
  flex-shrink: 0;
}

.comment-content {
  flex: 1;
}

.comment-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 8px;
}

.comment-author {
  font-weight: 600;
  color: #2c3e50;
  font-size: 14px;
}

.comment-time {
  color: #909399;
  font-size: 12px;
}

.comment-text {
  color: #303133;
  line-height: 1.6;
  margin-bottom: 12px;
  font-size: 14px;
}

.comment-actions {
  display: flex;
  gap: 12px;
}

.reply-list {
  margin-left: 56px;
  position: relative;
}

.reply-list::before {
  content: '';
  position: absolute;
  left: -20px;
  top: 0;
  bottom: 0;
  width: 2px;
  background: #ebeef5;
}

.nested-comments .comment-item {
  margin-top: 12px;
}

.comment-item.level-1 {
  background: #fff;
  border: 1px solid #ebeef5;
}

.comment-item.level-2 {
  background: #f8f9fa;
}

.comment-item.level-3 {
  background: #fff;
  border: 1px solid #ebeef5;
}

.comment-item.level-4 {
  background: #f8f9fa;
}

.comment-item.level-5 {
  background: #fff;
  border: 1px solid #ebeef5;
}

.reply-input {
  margin-top: 12px;
  padding: 12px;
  background: #fff;
  border-radius: 8px;
  border: 1px solid #ebeef5;
}

.reply-actions {
  display: flex;
  justify-content: flex-end;
  gap: 8px;
  margin-top: 8px;
}

.delete-btn {
  color: #f56c6c;
}

.delete-btn:hover {
  color: #f78989;
}

.comment-pagination {
  margin-top: 24px;
  display: flex;
  justify-content: center;
}

.comment-pagination .el-pagination {
  padding: 0;
}

.comment-pagination .el-pagination .el-pager li {
  background: #fff;
  border: 1px solid #e4e7ed;
  border-radius: 4px;
  margin: 0 4px;
  min-width: 30px;
  height: 28px;
  line-height: 28px;
  font-size: 13px;
  transition: all 0.3s ease;
}

.comment-pagination .el-pagination .el-pager li:hover {
  color: #409EFF;
  border-color: #409EFF;
}

.comment-pagination .el-pagination .el-pager li.active {
  background: #409EFF;
  color: #fff;
  border-color: #409EFF;
}

.comment-pagination .el-pagination .btn-prev,
.comment-pagination .el-pagination .btn-next {
  background: #fff;
  border: 1px solid #e4e7ed;
  border-radius: 4px;
  padding: 0 8px;
  margin: 0 4px;
  min-width: 30px;
  height: 28px;
  line-height: 28px;
  transition: all 0.3s ease;
}

.comment-pagination .el-pagination .btn-prev:hover,
.comment-pagination .el-pagination .btn-next:hover {
  color: #409EFF;
  border-color: #409EFF;
}

.comment-pagination .el-pagination .el-pagination__sizes {
  margin-right: 10px;
}

.comment-pagination .el-pagination .el-pagination__jump {
  margin-left: 10px;
}

.subscribe-info {
  margin-top: 20px;
  padding: 10px;
  background-color: #f5f7fa;
  border-radius: 4px;
}

.nested-comments {
  width: 100%;
}

.reply-list {
  margin-left: 56px;
  position: relative;
  padding-left: 20px;
}

.reply-list::before {
  content: '';
  position: absolute;
  left: 0;
  top: 0;
  bottom: 0;
  width: 2px;
  background: #ebeef5;
}

.comment-item.level-1 {
  background: #fff;
  border: 1px solid #ebeef5;
  margin-bottom: 12px;
}

.comment-item.level-2 {
  background: #f8f9fa;
  margin-bottom: 12px;
}

.comment-item.level-3 {
  background: #fff;
  border: 1px solid #ebeef5;
  margin-bottom: 12px;
}

.comment-item.level-4 {
  background: #f8f9fa;
  margin-bottom: 12px;
}

.comment-item.level-5 {
  background: #fff;
  border: 1px solid #ebeef5;
  margin-bottom: 12px;
}

.comment-thread {
  margin-bottom: 0;
}

.comment-thread:last-child {
  margin-bottom: 20px;
}

.novel-actions {
  display: flex;
  gap: 10px;
}

.reward-btn, .pass-btn {
  padding: 10px 20px;
  border-radius: 20px;
  transition: all 0.3s ease;
  color: white;
  border: none;
}

.reward-btn {
  background: #f56c6c;
}

.reward-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(245, 108, 108, 0.3);
  background: #f78989;
}

.pass-btn {
  background: #e6a23c;
}

.pass-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(230, 162, 60, 0.3);
  background: #ebb563;
}

.reward-btn i, .pass-btn i {
  margin-right: 5px;
}

.reward-dialog {
  padding: 10px;
}

.reward-options {
  display: flex;
  flex-wrap: wrap;
  gap: 15px;
  margin-bottom: 20px;
}

.reward-option {
  width: calc(33.33% - 10px);
  padding: 15px 10px;
  border-radius: 8px;
  border: 1px solid #ebeef5;
  text-align: center;
  cursor: pointer;
  transition: all 0.3s ease;
}

.reward-option:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.reward-option.active {
  border-color: #f56c6c;
  background: #fff5f5;
}

.reward-icon {
  font-size: 24px;
  color: #f56c6c;
  margin-bottom: 8px;
}

.reward-value {
  font-weight: 600;
  color: #2c3e50;
  margin-bottom: 4px;
}

.reward-points {
  font-size: 12px;
  color: #909399;
}

.reward-message {
  margin-bottom: 15px;
}

.reward-info {
  background: #f8f9fa;
  padding: 10px;
  border-radius: 8px;
  font-size: 14px;
  color: #606f7b;
}

.reward-info p {
  margin: 5px 0;
}

.pass-dialog {
  padding: 10px;
}

.pass-options {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.pass-input {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 10px;
}

.pass-label {
  font-size: 16px;
  font-weight: 600;
  color: #2c3e50;
}

.pass-info {
  background: #f8f9fa;
  padding: 15px;
  border-radius: 8px;
  font-size: 14px;
  color: #606f7b;
}

.pass-info p {
  margin: 8px 0;
  display: flex;
  justify-content: space-between;
}

.pass-info p:first-child {
  color: #e6a23c;
  font-weight: 600;
}

.bookshelf-btn {
  padding: 10px 20px;
  border-radius: 20px;
  transition: all 0.3s ease;
  border: 1px solid #dcdfe6;
  background: #fff;
  color: #606f7b;
}

.bookshelf-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.bookshelf-btn.in-bookshelf {
  background: #67c23a;
  color: white;
  border-color: #67c23a;
}

.bookshelf-btn.in-bookshelf:hover {
  background: #85ce61;
}

.bookshelf-btn i {
  margin-right: 5px;
}
</style> 